/**
 * 订单信息
 */
var orderInfo = {
	ORDERID : orderId,
	ORDERKEY : orderKey
};
var payUserInfoList = [];
var URL_GetOrderInfo = "webGetOrderInfo.json";// 查询获取订单信息
var URL_GetPayUserInfo = "webGetPayUserInfo.json";// 查询支付者信息
var URL_GetVerificationCode = "webGetVerificationCode.json";// 获取验证码
var URL_GetVerificationCodeAgain = "webGetCodeAgain.json";// 重新获取验证码
var URL_SUCCESS = "webpay/order_show.jsp?orderId=" + orderId + "&orderKey="
		+ orderKey;
var URL_PAY_PAGE = "webpay/order_pay.jsp?orderId=" + orderId + "&orderKey="
+ orderKey;
var URL_Pay = "webPay.json";// 订单支付
var URL_Agreement = "webpay/agreement.jsp";
var URL_REMOVE_CARD = "webRemoveCard.json";

var MSG_IDO = "如果您确定要使用【口袋支付】,请认真阅读并同意口袋支付的协议后再操作。";

var RSPCOD_SUCCESS = "000000";

var ORDER_INFO_TEXT = "尊敬的口袋支付用户，商户${CUST_NAME}正在发起一笔金额为【￥${ORDAMT}元】的收款，订单号为【${ORDERID}】,如有疑问请拨打口袋支付客户服务热线：400-999-4048";

/**
 * 得到订单的表单对象
 * 
 * @returns
 */
function getOrderForm() {
	return $("#orderPayForm");
}
function getOrderTable() {
	return $(".orderPayTable");
}
/**
 * 获取订单信息
 */
function getOrderInfo() {
	// var form = getOrderForm();
	var data = $.extend({}, orderInfo);
	var url = $.getBaseHerf() + URL_GetOrderInfo;
	formSubmitForAjax({
		url : url,
		data : data,
		success : function(json) {
			try {
				if (json.RSPCOD == RSPCOD_SUCCESS) {
					orderInfo = $.extend({}, orderInfo, json.ORDERINFO);
					var ORDSTATUS = orderInfo['ORDSTATUS'];
					// 如果订单已经支付完成，直接跳转到订单查询页面 ( ORDSTATUS == '02' 支付失败可以重新支付)
					if (ORDSTATUS == '01') {
						 $(".order-tonext").hide();
						 openToOrderInfo();
					}else if(ORDSTATUS == '-1'){//-1已失效
						$(".order-tonext").hide();
					}else{
						$(".order-tonext").show();
					}

					var $form = getOrderForm();
					if ($form && $form.length > 0) {
						// 表单填充
						fillForm(getOrderForm(), orderInfo);
					}

					var $table = getOrderTable();
					if ($table && $table.length > 0) {
						// 填充表格
						fillTable($table, orderInfo);
					}
				} else {
					alert(json.RSPMSG);
				}
			} catch (e) {
				alert("订单信息查询失败！");
			}
		}
	});
}

var checkCodeClick = true;
var payClick = true;
var GET_CHECK_CODE_NUM = 0;// 获取验证码次数
var timing = 90;
var time_code = timing;// 验证码定时

/**
 * 获取验证码
 */
/*function getVerificationCode() {
	// 防止重复点击、多次点击“获取验证码”,在返回后要改变其值为true，表示允许再次点击(成功倒计时的情况在计时完成后改变)
	if (checkCodeClick === false) {
		return;
	}

	var $form = getOrderForm();
	var ok = TDValidateForm($form);

	if (ok) {
		var url = $.getBaseHerf() + URL_GetVerificationCode;
		if (GET_CHECK_CODE_NUM > 0) {// 获取次数超过一次，要重新获取验证码
			url = $.getBaseHerf() + URL_GetVerificationCodeAgain;
		}
		var data = getFormParams($form);
		if (!iDo(data)) {
			alert(MSG_IDO);
			return;
		}

		checkCodeClick = false;

		formSubmitForAjax({
			url : url,
			data : data,
			success : function(json) {
				try {
					if (json.RSPCOD == RSPCOD_SUCCESS) {
						// 防止重复点击、多次点击“获取验证码”,在返回后要改变其值为true，表示允许再次点击(成功倒计时的情况在计时完成后改变)
						checkCodeClick = false;
						// 倒计时
						countdown();
						GET_CHECK_CODE_NUM = GET_CHECK_CODE_NUM + 1;
					} else if(json.RSPMSG == '非待验证订单，无须发送验证码'){
						checkCodeClick = true;
						alert("由于该笔订单已支付失败，请联系收款人重新发起收款操作！支付前请仔细核对输入的信息，以避免此类情况的发生，谢谢！");
					} else {
						checkCodeClick = true;
						if ("20019" == json.RSPCOD || "订单已存在" == json.RSPMSG) {// 如果已经获取过验证码，重新获取
							if(GET_CHECK_CODE_NUM > 0){
								alert("由于该笔订单已支付失败，请联系收款人重新发起收款操作！支付前请仔细核对输入的信息，以避免此类情况的发生，谢谢！");
							}else{
								getVerificationCode();
							}
							GET_CHECK_CODE_NUM = GET_CHECK_CODE_NUM + 1;
						} else {
							alert(json.RSPMSG);
						}
					}
				} catch (e) {
					checkCodeClick = true;
					alert("验证码获取失败，请重试!");
				}
			},
			error : function() {
				checkCodeClick = true;
				alert("验证码获取失败，请重试!");
			}
		});
	}
}*/

/**
 * 获取验证码
 */
function getVerificationCode() {
	// 防止重复点击、多次点击“获取验证码”,在返回后要改变其值为true，表示允许再次点击(成功倒计时的情况在计时完成后改变)
	if (checkCodeClick === false) {
		doPayBtn(1);
		return;
	}

	var $form = getOrderForm();
	var ok = TDValidateForm($form);

	if (ok) {
		var url = $.getBaseHerf() + URL_GetVerificationCodeAgain;
		var data = getFormParams($form);
		var channel = data["PAY_CHANNELS"];
		if(channel == "YIBAO"){
			data["CMD"] = "get_pin";
		}else if(channel == "RUNFUTONG"){
			data["CMD"] = "rb_get_pin";
		}
		if (!iDo(data)) {
			alert(MSG_IDO);
			doPayBtn(1);
			return;
		}

		checkCodeClick = false;

		formSubmitForAjax({
			url : url,
			data : data,
			success : function(json) {
				try {
					if (json.RSPCOD == RSPCOD_SUCCESS) {
						// 防止重复点击、多次点击“获取验证码”,在返回后要改变其值为true，表示允许再次点击(成功倒计时的情况在计时完成后改变)
						checkCodeClick = false;
						// 倒计时
						countdown();
						GET_CHECK_CODE_NUM = GET_CHECK_CODE_NUM + 1;
					}else{
						checkCodeClick = true;
					}
				} catch (e) {
					checkCodeClick = true;
					alert("验证码获取失败，请重试!");
				}
				doPayBtn(1);
			},
			error : function() {
				checkCodeClick = true;
				alert("验证码获取失败，请重试!");
			}
		});
	}else{
		doPayBtn(1);
	}
}

/**
 * 提交支付卡号信息 - 易宝
 */
function submitCardInf() {
	var $form = getOrderForm();
	var ok = TDValidateForm($form);

	if (ok) {
		var url = $.getBaseHerf() + URL_GetVerificationCode;
		var data = getFormParams($form);
		var channel = data["PAY_CHANNELS"];
		var cardType = data["CARD_TYPE"];
		if(channel == "YIBAO"){
			if(cardType == "01"){//借记卡
				data["CMD"] = "DebitCardPay";
			}else{//信用卡
				data["CMD"] = "CreditCardPay";
			}
		}else if(channel == "RUNFUTONG"){
			if(cardType == "01"){//借记卡
				alert("该渠道只支持信用卡支付");
				doPayBtn(1);
				return;
			}else{//信用卡
				data["CMD"] = "rb_mer";
			}
		}
		if (!iDo(data)) {
			alert(MSG_IDO);
			doPayBtn(1);
			return;
		}

		checkCodeClick = false;

		formSubmitForAjax({
			url : url,
			data : data,
			success : function(json) {
				try {
					if (json.RSPCOD == RSPCOD_SUCCESS) {
						var ORD_ID = json["ORD_ID"];
						var SMSCONFIRM = json['SMSCONFIRM'] || "";
//						$("input[name='ORD_ID']").val(ORD_ID);
						var $verifyCode = $("#form_verifyCode");
						GET_CHECK_CODE_NUM = 0;
						if(SMSCONFIRM == "1"){//需要发送短信验证码
							checkCodeClick = true;
							$verifyCode.show();//显示获取验证码框
							//自动获取验证码
							getVerificationCode();
							var $btnPay = $("#btn_pay");
							doBtn($btnPay,1);
						}else if(SMSCONFIRM == "0"){//可以不发送短信验证码
							checkCodeClick = false;
							$verifyCode.hide();
							//不需要验证码的话直接支付
							orderPay();
						}
					}else {
						checkCodeClick = true;
						alert(json.RSPMSG);
						var $btnPay = $("#btn_pay");
						doBtn($btnPay,1);
					}
				} catch (e) {
					checkCodeClick = true;
					alert("提交失败，请重试!");
					var $btnPay = $("#btn_pay");
					doBtn($btnPay,1);
				}
			},
			error : function() {
				checkCodeClick = true;
				alert("提交失败，请重试!");
			}
		});
	}else{
		doPayBtn(1);
	}
}

/**
 * 获取支付者信息
 * 
 */
function getPayUserInfo() {
	var $form = getOrderForm();
	var url = $.getBaseHerf() + URL_GetPayUserInfo;
	var data = orderInfo;
	formSubmitForAjax({
		url : url,
		data : data,
		success : function(json) {
			try {
				if (json.RSPCOD == RSPCOD_SUCCESS) {
					payUserInfoList = json.CARDLIST;
					var len = payUserInfoList.length;
					if(len > 0){
//						$('.card-list-box').before('<row><div class="col-xs-12 col-sm-12 order-desc">下列是您使用过的银行卡(卡号后四位)</div></row>');
						var html = createCardOptions(payUserInfoList);
						var $cardListView = $('.card-list-view');
						$cardListView.html(html);
					
//						$('.card-list-box').after('<div class="space-4"></div>');
						$('.card-list-box').show();
					}
					//创建历史卡片选择列表
//					if (payUserInfoList && payUserInfoList.length > 0) {
//						fillForm(getOrderForm(), payUserInfoList[0]);
//					}

				} else {
					// alert(json.RSPMSG);
				}
			} catch (e) {
				// alert("查询账号信息失败，请重试!");
			}
		}
	});
}

function cardViewClick($this,idx){
	if(idx == undefined){
		return;
	}
	var $div = $($this);
//	alert($div);
	$('.card-view li').remove();
	var li = '<i class="ace-icon fa fa-check-square-o"></i>';
//	$div.html($div.html() + li);
	var cardInfo = payUserInfoList[idx];
	//清除上一次输入的CVV码
	$('input[name="CVV"]').val("");
	fillForm(getOrderForm(),cardInfo );
	
	//如果不是点击的单选按钮，要让单选按钮选中
	$('input[type="radio"]',$this).attr("checked","checked");
}

function removeCard(e,$this,idx){
	e.stopPropagation();
	var r = confirm("您确定要删除该银行卡记录吗？");
	if (r == false) {
		return;
	}
	
	var url = $.getBaseHerf() + URL_REMOVE_CARD;
	var $form = getOrderForm();
	var data = getFormParams($form);
	var cardNo = payUserInfoList[idx]['BANKNO'];
	$this = $($this);
	
	if(!cardNo){
		return;
	}
	
	data['BANKNO'] = cardNo;
	formSubmitForAjax({
		url : url,
		data : data,
		success : function(json) {
			try {
				if (json.RSPCOD == RSPCOD_SUCCESS) {
//					alert("删除成功");
					//删除div
					$this.parents(".card-view").remove();
					//如果一项银行卡信息都没有了，将选择行隐藏
					if($('.card-view').length == 0){
						$('.card-list-box').hide();
					}
				} else {
					// alert(json.RSPMSG);
				}
			} catch (e) {
				// alert("查询账号信息失败，请重试!");
			}
		}
	});
}

function createCardOptions(cardList){
	var html = '';
	var len = cardList.length;
	if(!cardList || len == 0){
		return html;
	}
//	for(var i=0;i<10;i++){
//		html += createCardOption(cardList[0],0);
//	}
	for(var i=0;i<len;i++){
		html += createCardOption(cardList[i],i);
	}
	return html
}

function createCardOption(cardInfo,idx){
	var html = '';
	if(!cardInfo){
		return html;
	}
	var cardNo = cardInfo['BANKNO'];
	if(cardNo){
		html += '<div class="col-xs-4 col-sm-4 card-view" onclick="cardViewClick(this,'+idx+')">';
//		html += '<label><input name="t_card" class="ace" type="radio"><span class="lbl"> *'+cardNo.substring(cardNo.length-4)+'</span></label><i class="ace-icon glyphicon glyphicon-remove" onclick="removeCard(event,this,'+idx+')"></i>';
		html += '<label><input name="t_card" class="ace" type="radio"><span class="lbl"> *'+cardNo.substring(cardNo.length-4)+'</span></label><i class="remove-card" onclick="removeCard(event,this,'+idx+')">x</i>';
//		html += cardNo.substring(cardNo.length-4);
		html += '</div>';
		return html;
	}
}

/** 倒计时 */
function countdown() {
	var $btn = $(".check-code");
	if (time_code < 0) {
		time_code = timing;
		$btn.html("重新获取验证码").removeAttr("disabled");
		checkCodeClick = true;
		return;
	}

	$btn.html(time_code + " 秒").attr("disabled", "disabled");

	time_code = time_code - 1;

	setTimeout(countdown, 1000);
}

/**
 * 提交验证码
 */
function orderPay() {
	if(!payClick){
		doPayBtn(1);
		return;
	}
	var $form = getOrderForm();
	var url = $.getBaseHerf() + URL_Pay;
	var data = getFormParams($form);
	
	var channel = data["PAY_CHANNELS"];
	if(channel == "YIBAO"){
		data["CMD"] = "pay";
	}else if(channel == "RUNFUTONG"){
		data["CMD"] = "rb_pin";
	}
	
	var ok = TDValidateForm($form);
	if(!ok){
		doPayBtn(1);
		return;
	}
	var checkCode = data['VERIFYCODE'];
	var $yzmBox = $("#form_verifyCode");
	//如果验证码是隐藏的，走以前获取验证码提交支付信息接口，会一次性把流程走完
	if(!$yzmBox.is(":hidden")){//不需要验证码
		if (!checkCode) {
			alert("请输入有效的验证码");
			doPayBtn(1);
			return;
		}
		if(!(/^\d{3}$/.test(checkCode)) && !(/^\d{6}$/.test(checkCode))){
			alert("请输入有效的验证码");
			doPayBtn(1);
			return;
		}
	}
	if (!iDo(data)) {
		alert(MSG_IDO);
		doPayBtn(1);
		return;
	}
	var r = confirm("您确定要进行支付吗？该操作将从您的银行卡内扣款并转入商户账户， 请确认您在知晓该笔交易的情况下付款，口袋支付工作人员不会以任何形式向您索取短信验证码及内容，谨防上当受骗，如有疑问请拨口袋支付官方服务热线 400-999-4048 咨询或举报 ");
	if (r == false) {
		doPayBtn(1);
		return;
	} 
	payClick = false;
	formSubmitForAjax({
		url : url,
		data : data,
		success : function(json) {
			try {
				if (json.RSPCOD == RSPCOD_SUCCESS) {
					delayToOrderInfo();//延时跳转到订单查询
					
					// 支付成功
//					alert(json.RSPMSG);
//					setTimeout(openToOrderInfo, 1500);
//					openToOrderInfo();
				} else {
					alert(json.RSPMSG);
				}
			} catch (e) {
				alert("操作失败!");
			}
			doPayBtn(1);
			payClick = true;
		},
		error : function() {
			alert("支付失败，请重试!");
			payClick = true;
			var $btnPay = $("#btn_pay");
			doBtn($btnPay,1);
		}
	});
}

var delayTime = 7;//延时跳转到订单查询的页面的时间 秒

function delayToOrderInfo(){
	$(".countdown_box").show();
	$(".countdown_content").html("<span style='color:green;'>交易完成</span><br>查看支付结果请等待 <span style='color:red;'>" + delayTime + "</span> 秒");
	if(delayTime > 0){
		delayTime = delayTime -1;
		setTimeout(delayToOrderInfo, 1000);
		return;
	}
	openToOrderInfo();
}

function openTo(url, type) {
	if (window.location == url) {
		return;
	}
	if (type == 1) {
		window.open(url);
	} else {
		window.location = url;
	}
}

function openToOrderInfo() {
	var url = $.getBaseHerf() + URL_SUCCESS;
	openTo($.getBaseHerf() + URL_SUCCESS);
}

function openAgreement() {
	var url = $.getBaseHerf() + URL_Agreement;
	openTo(url, 1);
}

function toPayPage(){
	var url = $.getBaseHerf() + URL_PAY_PAGE;
	openTo(url);
}

function iDo(data) {
//	var $iDo = $("input[name='iDo']");
	if (data['iDo'] == 1) {
		return true;
	} else {
		false;
	}
	return false;
}

function doPayBtn(s){
	var $btnPay = $("#btn_pay");
	if(s == 1){
		doBtn($btnPay,1);
	}else{
		doBtn($btnPay,0);
	}
}

// 加载完成执行
$(document).ready(function() {
	$(".check-code").on("click", function() {
		getVerificationCode();
	});
	$.mask.definitions['m'] = '0|1';
	// $.mask.definitions['M']='[0-9]';
	$('.input-mask-date').mask('m9/99');
	// $('input[name=CVV]').mask('999');
	doBtn($(".check-code"),1);
//	$("input[name='ORD_ID']").val();
	
	var $btnPay = $("#btn_pay");
	doBtn($btnPay,1);
	$btnPay.on("click",function(){
		var $this = $(this);
		var $yzmBox = $("#form_verifyCode");
		doBtn($this,0);
		//如果验证码是隐藏的，走以前获取验证码提交支付信息接口，会一次性把流程走完
		if($yzmBox.is(":hidden")){
			submitCardInf();//提交卡号等信息
		}else{
			orderPay();//输入验证码以后支付
		}
//		doBtn($this,1);
	});
	
});

function readAgreement() {
	// openDialog({
	// title:"口袋支付消费者支付协议",
	// pageUrl :'webpay/agreement.jsp',
	// width : '98%',
	// height:'100%'
	// });

	openAgreement();
}
function reLoad(){
	$(".td-data",getOrderTable()).html("");
	getOrderInfo();
}
